﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
        }

        public void FillData()
        {
            var data = Dbhelper.GetData(string.Format("select id,Title,content,author,remarks from articles"));
            GridView1.DataSource = data;
            GridView1.DataBind();
        }

        public string GetValue(int rowindex,int cellindex)
        {
            var control = GridView1.Rows[rowindex].Cells[cellindex];
            var r = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return r;
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillData();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetValue(e.RowIndex,1);
            Dbhelper.AddOr(string.Format("delete from articles where id={0}",id));
            FillData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var id = GetValue(e.RowIndex,1);
            var title = GetValue(e.RowIndex, 2);
            var content = GetValue(e.RowIndex, 3);
            var author = GetValue(e.RowIndex, 4);
            var remarks = GetValue(e.RowIndex, 5);

            Dbhelper.AddOr(string.Format("update articles set title='{0}',content='{1}',author='{2}',remarks='{3}' where id='{4}'",title,content,author,remarks,id));
            GridView1.EditIndex = -1;
            FillData();

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Add.aspx");
        }
    }
}